#!/bin/bash
HOSTNAME="orangepi"
rootfs=$OPI_SYSTEM_OUTPUT_DIR
system=$OPI_SYSTEM_TYPE
version=$OPI_SYSTEM_VERSION
mirror=

if [ "$(id -u)" != "0" ]; then
   echo "Script must be run as root !"
   exit 0
fi

if  [[ $system == "debian" ]] ; then
	case  "$version"  in   
 	jessie ) 
		mirror="http://ftp.cn.debian.org/debian/"
		;;
	wheezy ) 
		mirror="http://ftp.cn.debian.org/debian/"
		;;
	esac
elif [[ $system == "ubuntu" ]] ; then
	case  "$version"  in
	xenial )
		mirror=	"http://mirrors.aliyun.com/ubuntu/"
		;;
	vivid ) 
		mirror="http://mirrors.aliyun.com/ubuntu/"
		;;
	trusty ) 
		mirror="http://mirrors.aliyun.com/ubuntu/"
		;;
	esac
elif [[ $system == "" ]] ; then
	echo "no select system!!!"
	exit 0
fi

message "check installed software ....."
	apt-get install -y -q binfmt-support qemu qemu-user-static debootstrap
echo ""
message " entry root file system dir " && cd $rootfs
echo ""

#debootstrap
message " run debootstrap...."
debootstrap --arch armhf $version $rootfs $mirror
echo ""
cp -rf /usr/bin/qemu-arm-static $rootfs/usr/bin

#set qemu
export LC_ALL=C 
export LANGUAGE=C 
export LANG=C
export DEBCONF_NONINTERACTIVE_SEEN=true 
export DEBIAN_FRONTEND=noninteractive

echo "debootstrap second-stage"
DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true LC_ALL=C LANGUAGE=C LANG=C chroot $rootfs /debootstrap/debootstrap --second-stage

cp -rf $rootfs/../../config/apt-source/sources.list.$version  $rootfs/etc/apt/sources.list
if  [[ $system == "debian" ]] ; then
cp -rf $rootfs/../../script/build_rootfs_last_stage_debian  $rootfs/init.sh
elif [[ $system == "ubuntu" ]] ; then
cp -rf $rootfs/../../script/build_rootfs_last_stage_ubuntu  $rootfs/init.sh 
fi
chmod 755 $rootfs/init.sh 
echo ""
echo "debootstrap last-stage"
DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true LC_ALL=C LANGUAGE=C LANG=C chroot $rootfs /init.sh
echo ""

times='date'
echo "system : $system " > $rootfs/OrangePi
echo "version : $version " >> $rootfs/OrangePi
echo "mirror : $mirror" >> $rootfs/OrangePi
echo "build time : $times" >> $rootfs/OrangePi

echo ""
message "make rootfs finish,Please to see $rootfs directories" 
echo "^_^"
#https://wiki.debian.org/EmDebian/CrossDebootstrap

